﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NRemedy.CodeGenerator.WinForm
{
    public partial class Main : Form
    {

        private SearchFormThread _searchFormThread;
        private CodeGenerateThread _codeGenerateThread;

        public Main()
        {
            InitializeComponent();
            SetUI();
            InitObject();
        }

        private void SetUI()
        {
            this.cmbFilterType.Items.Add(FilterType.Name.ToString());
            this.cmbFilterOperation.Items.Add(FilterOperation.contains.ToString());
            this.cmbFilterType.SelectedIndex = 0;
            this.cmbFilterOperation.SelectedIndex = 0;


            this.txtFilterValue.KeyDown += new KeyEventHandler(txtFilterValue_KeyDown);
            this.tvwFormList.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(tvwFormList_NodeMouseDoubleClick);
            this.mitemCopyAll.Click += new EventHandler(mitemCopyAll_Click);
        }

        private void mitemCopyAll_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(txtCodeArea.Text, true);
        }

        private void tvwFormList_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (!_codeGenerateThread.IsRunning())
            {

                _codeGenerateThread.Start(e.Node.Text);
            }
        }

        private void InitObject()
        {
            _searchFormThread = new SearchFormThread();
            _searchFormThread.SearchCompeleted += new PushFormListDelegate(_searchFormThread_SearchCompeleted);
            _codeGenerateThread = new CodeGenerateThread();
            _codeGenerateThread.GenerateCompeleted += new PushCodeDelegate(_codeGenerateThread_GenerateCompeleted);

        }

        private void _searchFormThread_SearchCompeleted(IEnumerable<ARFormDisplay> formList)
        {

            tvwFormList.Nodes.Clear();
            foreach (var f in formList)
            {
                TreeNode tn = new TreeNode(f.Name);
                tvwFormList.Nodes.Add(tn);
            }
        }


        private void _codeGenerateThread_GenerateCompeleted(string code)
        {
            this.txtCodeArea.Text = code;
        }

        private void txtFilterValue_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!_searchFormThread.IsRunning())
                {
                    _searchFormThread.Start(cmbFilterType.SelectedItem, cmbFilterOperation.SelectedItem, txtFilterValue.Text);
                }
            }
        }
    }
}
